package com.demoworld;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {


    public static void main(String[] args) {
        futureDemo();
        
        serialDemo();
    }

    private static void futureDemo() {
        DataHolder<Integer> n1 = new DataHolder<>();
        CompletableFuture<Integer> tmp1 = CompletableFuture.supplyAsync(() -> {
            int n = taskOne();
            n1.setData(n);
            return 1;
        });
        DataHolder<String> n2 = new DataHolder<>();
        CompletableFuture<Integer> tmp2 = CompletableFuture.supplyAsync(() -> {
            String n = taskTwo();
            n2.setData(n);
            return 2;
        });
        DataHolder<Float> n3 = new DataHolder<>();
        CompletableFuture<Integer> tmp3 = CompletableFuture.supplyAsync(() -> {
            float n = taskThree();
            n3.setData(n);
            return 3;
        });
        CompletableFuture<Integer>[] tmpArray = new CompletableFuture[3];
        tmpArray[0] = tmp1;
        tmpArray[1] = tmp2;
        tmpArray[2] = tmp3;

        long start = System.currentTimeMillis();
        CompletableFuture allOf = CompletableFuture.allOf(tmpArray);
        Object o = null;
        try {
            o = allOf.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(String.format("1=%d, 2=%s, 3=%f", n1.getData(), n2.getData(), n3.getData()));
        System.out.println("并行耗时=" + (end - start));
    }

    private static void serialDemo() {
        long start = System.currentTimeMillis();
        taskThree();
        taskTwo();
        taskOne();
        long end = System.currentTimeMillis();

        System.out.println("串行耗时=" + (end - start));
    }

    public static int taskOne() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 1 =" + (end - start));
        return 1;
    }

    public static String taskTwo() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 2 =" + (end - start));
        return "2";
    }

    public static float taskThree() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 3 =" + (end - start));
        return 3.1f;
    }
}
